angular
    .module('directory.directoryadd.svc', ['kd.orm.svc', 'alert.svc'])
    .service('DirectoryaddSvc', DirectoryaddSvc);

    DirectoryaddSvc.$inject = ['$http', '$q', '$filter', 'KdOrmSvc', 'AlertSvc', 'UtilsSvc', '$window'];

function DirectoryaddSvc($http, $q, $filter, KdOrmSvc, AlertSvc, UtilsSvc, $window) {

    var models = {
        Genders: 'User.Genders',
        Nationalities: 'FieldOption.Nationalities'
    };

    var service = {
        init: init,
        getUniqueOpenEmisId: getUniqueOpenEmisId,
        generatePassword: generatePassword,
        getUserTypes: getUserTypes,
        getGenders: getGenders,
        getNationalities: getNationalities,
        getIdentityTypes: getIdentityTypes,
        getInternalSearchData: getInternalSearchData,
        getExternalSearchData: getExternalSearchData,
        getContactTypes: getContactTypes,
        getRedirectToGuardian: getRedirectToGuardian,
        getStudentCustomFields: getStudentCustomFields,
        getStaffCustomFields: getStaffCustomFields,
        getAddressAreaId: getAddressAreaId,
        getAddressArea: getAddressArea,
        getBirthplaceAreaId: getBirthplaceAreaId,
        getBirthplaceArea: getBirthplaceArea,
        saveDirectoryData: saveDirectoryData,
        checkUserAlreadyExistByIdentity: checkUserAlreadyExistByIdentity,
        checkConfigForExternalSearch: checkConfigForExternalSearch,
        getCspdData: getCspdData,
    };
    return service;

    function init(baseUrl){
        KdOrmSvc.base(baseUrl);
        KdOrmSvc.controllerAction('Directory');
        KdOrmSvc.init(models);
    }

    function getUniqueOpenEmisId() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getUniqueOpenemisId/';
        // console.log(url);
        $http.get(url)
        .then(function(response){
            // console.log("response");
            // console.log(response);
            deferred.resolve(response.data.openemis_no);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function generatePassword() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getAutoGeneratedPassword/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response.data.password);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getUserTypes() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getUserType/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getGenders() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getGenders/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getNationalities() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getNationalities/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getIdentityTypes() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getIdentityTypes/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

    function getContactTypes() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getContactType/';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

    function getInternalSearchData(params) {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/directoryInternalSearch';
        $http.post(url, {params: params})
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

    function getExternalSearchData(params) {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/directoryExternalSearch';
        $http.post(url, {params: params})
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

    function getRedirectToGuardian() {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Directories/getRedirectToGuardian';
        $http.get(url)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    };

    function getStudentCustomFields(userId){
        var params = {
            student_id: userId
        };
        var deferred = $q.defer();
        let url = angular.baseUrl + '/Institutions/studentCustomFields';
        $http.post(url, {params: params})
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getStaffCustomFields(staffId){
        var params = {
            staff_id: staffId,
        };
        var deferred = $q.defer();
        let url = angular.baseUrl + '/Institutions/staffCustomFields';
        $http.post(url, {params: params})
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    function getAddressAreaId () {
        selectedAddressAreaId = $window.localStorage.getItem('address_area_id');
        return JSON.parse(selectedAddressAreaId);
    }

    function getAddressArea () {
        selectedAddressArea = $window.localStorage.getItem('address_area');
        return JSON.parse(selectedAddressArea);
    }

    function getBirthplaceAreaId () {
        selectedBirthplcaeAreaId = $window.localStorage.getItem('birthplace_area_id');
        return JSON.parse(selectedBirthplcaeAreaId);
    }

    function getBirthplaceArea () {
        selectedBirthplcaeArea = $window.localStorage.getItem('birthplace_area');
        return JSON.parse(selectedBirthplcaeArea);
    }

    function saveDirectoryData (params) {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Institution/Institutions/saveDirectoryData';
        $http.post(url, params)
        .then(function(response){
            deferred.resolve(response);
        }, function(error) {
            deferred.reject(error);
        });
        return deferred.promise;
    }

    /**
     * Parameters are - identity_type_id, identity_number & nationality_id pass as a object
     * If staff exist then user_exist will be 1 otherwise 0 & show the message as warning
     * @required {identity_type_id} identity_type_id
     * @required {identity_number} identity_number
     * @required {nationality_id} nationality_id
     * @returns {[{"user_exist":1,"status_code":2,"message":"User already exist with this nationality, identity type & identity type. Kindly select user from below list."}]}
     */
    function checkUserAlreadyExistByIdentity(params)
    {
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Institutions/checkUserAlreadyExistByIdentity';
        $http.post(url, { params: params })
            .then(function (response)
            {
                deferred.resolve(response);
            }, function (error)
            {
                deferred.reject(error);
            });
        return deferred.promise;
    }

    /**
    * Based on showExternalSearch property need to hide external search step in form wizard
    * @returns {Case 1: for None  [{"value":"None","showExternalSearch ":false}]}
   *  @returns {Case 2: for rest values [{"value":"OpenEMIS Identity","showExternalSearch ":true}]}
    */
    function checkConfigForExternalSearch(nationality_id, identity_type_id)
    {
        var deferred = $q.defer();
        let url = angular.baseUrl + '/Institutions/checkConfigurationForExternalSearch';
        let params = {
            'nationality_id' : nationality_id,
            'identity_type_id' : identity_type_id
        };
        $http.post(url, {params: params})
            .then(function (response)
            {
                deferred.resolve(response.data[0]);
            }, function (error)
            {
                deferred.reject(error);
            });
        return deferred.promise;
    }


    /**
     * @name  Url: /Institutions/getCspdData
     * @description  Request Params: identity_number
     * @param {*} param  {identity_number}
     * @returns { "status_code":200,"message":"Get user details successfully.","data":{"third_name":"\u062d\u0633\u0646","nationality_name":"\u0627\u0631\u062f\u0646\u064a","gender_id":1,"gender_name":"Male","date_of_birth":"1979-02-15","address":"\u0627\u0644\u0630\u0631\u0627\u0639\/\u0642\u0635\u0628\u0629 \u0639\u0645\u0627\u0646","identity_type_id":160,"identity_type_name":"Birth Certificate","middle_name":"\u0635\u0627\u0644\u062d","postal_code":"0011101100601","first_name":"\u062d\u0633\u0646","identity_number":"9791048083","last_name":"\u062e\u0644\u064a\u0644","mother_national_no":"9552016857","father_national_no":"9551018573"}}
     */

    function getCspdData(params){
        var deferred = $q.defer();
        var url = angular.baseUrl + '/Institutions/getCspdData';
        $http.post(url, { params: params })
            .then(function (response)
            {
                deferred.resolve(response);
            }, function (error)
            {
                deferred.reject(error);
            });
        return deferred.promise;
    }
};
